package com.infocollect.project.wx.controller;

import com.infocollect.common.constant.Constants;
import com.infocollect.common.sms.MascloudSmsUtil;
import com.infocollect.common.sms.MessageSenderUtil;
import com.infocollect.common.utils.http.HttpUtils;
import com.infocollect.framework.redis.RedisCache;
import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.project.system.service.ISysDictTypeService;
import com.infocollect.project.wx.interceptor.WXPermission;
import org.apache.commons.lang.StringUtils;
import org.apache.juli.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.infocollect.common.utils.ServletUtils;
import com.infocollect.common.utils.sign.AES;
import com.infocollect.project.wx.utils.WxUserUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;

import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author Edward
 */
@Api("微信公众号验证")
@AllArgsConstructor
@RestController
@RequestMapping("/wx")
public class WxAuthController {
    private static final Logger log = LoggerFactory.getLogger(WxAuthController.class);
    private final WxMpService wxService;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDictTypeService dictTypeService;

    private static final String PHONE_CODE = "PHONE_CODE";
    /**
     * 组织获取用户openid时的url
     * @param redirectUri
     * @param state
     * @param map
     * @return
     */

    @ApiOperation(value = "组织获取用户openid时的url")
    @GetMapping("/redirect/index")
    public String index(@RequestParam String redirectUri, @RequestParam(required = false,value="state") String state, ModelMap map) {
    	String hostName = ServletUtils.getRequest().getServerName();
    	String returnUrl = "http://%s/wx/redirect/auth?redirectUri=%s";
    	String url = wxService.getOAuth2Service().buildAuthorizationUrl(
			String.format(returnUrl, hostName, AES.encode(redirectUri)), 
			"snsapi_base", state
    	);
    	return "redirect:" + url;
    }
    
    /**
     * 获取openid
     * @param code
     * @return
     */
    @ApiOperation(value = "从token获取openid")
    @GetMapping("/getOpenId")
    public AjaxResult getOpenId(@RequestParam String code) {
        try {
            WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
            String openId = accessToken.getOpenId();
            if(StringUtils.isBlank(openId)) {
                return AjaxResult.error("error");
            }
            return AjaxResult.success(openId);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return AjaxResult.error("error");
        }

    }
    @ApiOperation(value = "获取手机验证码")
    @GetMapping("/getPhoneCode")
    public AjaxResult getPhoneCode(@RequestParam String phone) {
        String key = PHONE_CODE + phone;
        String val = "";
        val = (String)redisCache.getCacheObject(key);
        if(com.infocollect.common.utils.StringUtils.isBlank(val)) {
            // 生成随机字串
            val = String.valueOf(Math.round((Math.random()+1) * 1000));//VerifyCodeUtils.generateVerifyCode(4);
            LinkedHashMap<String,String> smsMap = new LinkedHashMap<>();
            smsMap.put("hzcode",val);
            try {
                //MessageSenderUtil.getInstance().sendMessage(phone, "SMS_155270572", smsMap);
                MascloudSmsUtil.sendSms(phone,"你的验证码是："+val+"，20分钟内有效，请勿泄露给他人。");
                redisCache.setCacheObject(key, val, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            }catch(Exception ex){
                return AjaxResult.error("短信发送失败:"+ex.getMessage());
            }
        }
        log.info(val);
        return AjaxResult.success("success");
    }
    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        return AjaxResult.success(dictTypeService.selectDictDataByType(dictType));
    }
}
